package csu.jpetstore.jpetstore.service;

import csu.jpetstore.jpetstore.domain.AdminPermission;
import csu.jpetstore.jpetstore.repository.AdminPermissionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class AdminPermissionService {
    @Autowired
    AdminPermissionRepository adminPermissionRepository;
    @Autowired
    AdminRoleService adminRoleService;
    @Autowired
    AdminUserRoleService adminUserRoleService;
    @Autowired
    AdminRolePermissionService adminRolePermissionService;

    public AdminPermission getPermissionById(int permissionId){
        return adminPermissionRepository.findById(permissionId);
    }

    public List<AdminPermission> getPermissions(List<Integer> ids){
        List<AdminPermission> permissions = new ArrayList<>();
        for (Integer id : ids) {
            permissions.add(getPermissionById(id));
        }
        return permissions;
    }
    public List<String> getPermissionsUrlAndMethod(List<Integer> ids){
        List<String> urls = new ArrayList<>();
        for (Integer id : ids) {
            urls.add(getPermissionById(id).getPath()+":"+getPermissionById(id).getMethod());
        }
        return urls;
    }

    public List<String> getPermissionsUrlAndMethod(String userId){
        List<Integer> roleIds = adminUserRoleService.getRoleIdByUserId(userId);
        List<Integer> permissionIds = adminRolePermissionService.getPermissionIdByRoleId(roleIds);
        return getPermissionsUrlAndMethod(permissionIds);
    }

    public boolean needFilter(String requestAPI, String method){
        method = method.toLowerCase();
        List<AdminPermission> ps = adminPermissionRepository.findAll();
        for (AdminPermission p: ps) {
            if (p.getPath().equals(requestAPI)&&p.getMethod().equals(method)) {
                return true;
            }
        }
        return false;
    }
}
